package org.example.diet_compass.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.example.diet_compass.domain.LoginRequest;
import org.example.diet_compass.domain.Users;
import org.example.diet_compass.dto.MemberProfile;
import org.example.diet_compass.resp.Result;
import org.example.diet_compass.resp.ResultCodeEnum;
import org.example.diet_compass.service.ScoresService;
import org.example.diet_compass.service.UsersService;
import org.example.diet_compass.uitls.AccountGenerator;
import org.example.diet_compass.uitls.JwtUtil;
import org.modelmapper.ModelMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Archer_hui
 * @version 1.0
 * @Date 2025/3/2 10:39
 */
@Tag(name = "实现用户相关功能的控制器", description = "包括登录，个人信息管理等功能")
@RestController
@RequestMapping("/users")
public class UsersController {
    @Resource
    private UsersService usersService;


    @PostMapping("/login")
    @Operation(summary = "实现用户的登录方法")
    public Map<String, Object> userLogin(@RequestBody LoginRequest loginRequest) {
        Map<String, Object> model = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        // 1. 调用微信接口获取 openid 和 session_key
        String appId = "wx9d28b8ac9d3f6f8b";
        String appSecret = "abc66977184200899e5be52a2ebe60d2";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
                "&secret=" + appSecret + "&js_code=" + loginRequest.getCode() + "&grant_type=authorization_code";
        System.out.println(loginRequest.getCode()+"-----------------------");
        // 发送 HTTP 请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(response);

        // 2. 解析微信接口返回的数据
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        if (openid == null) {
            model.put("code", 500);
            model.put("message", "登录失败，无法获取 openid");
            return model;
        }

        // 3. 根据 openid 查询用户是否存在
        Users user = usersService.getUser(openid);

        // 4. 如果用户不存在，则创建新用户
        if (user == null) {
            user = new Users();
            user.setMobile("123456789");
            user.setAccount(AccountGenerator.generateAccount());
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            usersService.insertUser(user);
        }

        // 5. 生成自定义登录态（如 JWT token）
        String token = JwtUtil.generateToken(user.getId().toString());

        // 6. 返回结果
        model.put("code", 200);
        model.put("message", "登录成功");
        //token和user封装一下成data对象
        data.put("token", token);
        data.put("user", user);
        model.put("data", data);
        model.put("token", token);
        model.put("user", user);

        return model;
    }
    @Transactional
    @PutMapping("/update")
    public Result<Users> userUpdate(@RequestBody MemberProfile memberProfile,@RequestParam("id") int userId) {
        Users user = usersService.getUserById(userId);
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setSkipNullEnabled(true);//跳过空值
        modelMapper.map(memberProfile, user);//对象映射，将非空值更新到user中
        usersService.updateUserInfo(user);//更新
        //同时将新的user的信息返回
        return Result.build(user,ResultCodeEnum.SUCCESS);
    }

    @GetMapping("/getInfo")
    @Operation(summary = "获取用户信息的接口")
    public Result<Users>  getUserInfo(@RequestParam int id) {
        Users user = usersService.getUserById(id);
        if (user == null) {
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }else {
            return Result.build(user, ResultCodeEnum.SUCCESS);
        }

    }

    @PostMapping("/upload-avatar")
    @Operation(summary = "上传头像存储到服务器")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("id") int userId) {
        if (file.isEmpty()) {
            return Result.build(null, ResultCodeEnum.FILE_NULL);
        }
        try {
            // 保存文件到服务器或云存储
            String fileUrl = saveFile(file);
            // 将文件 URL 存储到数据库
            updateUserAvatar(userId, fileUrl);
            //返回头像访问url
            String avatarUrl = usersService.getAvatarUrlById(userId);
            return Result.build(avatarUrl,ResultCodeEnum.SUCCESS);
        } catch (Exception e) {
            return Result.build(null,ResultCodeEnum.FAIL);
        }
    }
    private String saveFile(MultipartFile file) throws Exception {
        // 保存文件到本地或云存储，并返回文件 URL
        // 示例：保存到本地
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String filePath = "G:\\diet_compass\\back_end\\avatar\\"+fileName;
        file.transferTo(new File(filePath));
        return "http://192.168.3.30:8080/"+fileName;
    }

    private void updateUserAvatar(int userId, String fileUrl) {
        // 更新用户头像 URL 到数据库
        usersService.updateUserAvatar(userId, fileUrl);
    }
}
